import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import { GroupTreeSelect } from '@/components/CustomForm';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { DownloadOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Button } from 'antd';
import dayjs from 'dayjs';
import { useRef } from 'react';

const getList = async (params) => {
  if (!params.groupId) {
    return {
      total: 0,
      data: [],
    };
  }
  const res = await request({
    url: '/datas/dmm/operation/vehicle/daily/cost/list',
    method: 'GET',
    custom: true,
    params: params,
  });
  let data = [];
  res?.data?.forEach((item) => {
    if (item?.operations?.length) {
      let items = item?.operations;
      items[0].rowSpan = items.length;
      items[0].groupName = item?.groupName;
      data = data.concat(items);
    } else {
      data.push({
        groupName: item?.groupName,
        rowSpan: 1,
      });
    }
  });
  console.log('data', data);

  return {
    total: data.length || 0,
    data: data || [],
  };
};

const Index = () => {
  const crudRef = useRef();

  const { data: groupData } = useRequest(async () => {
    const res = await request({
      url: '/base/group/list',
      method: 'get',
      params: {
        index: 0,
        size: 0,
      },
    });
    return res;
  });

  const columns = [
    // {
    //   title: '序号',
    //   fixed: 'left',
    //   width: 65,
    //   render: (text, record, index) => index + 1,
    // },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 200,
      onCell: (record) => {
        return {
          rowSpan: record.rowSpan || 0,
        };
      },
    },
    {
      title: '基本信息',
      children: [
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 120,
        },
        {
          title: '司机',
          dataIndex: 'realname',
          width: 220,
        },
        {
          title: '线路',
          dataIndex: 'lineName',
          width: 350,
        },
        {
          title: '公里数(km)',
          dataIndex: 'mileages',
          width: 120,
        },
      ],
    },
    {
      title: '收入信息',
      children: [
        {
          title: '拉运吨位(吨/方)',
          dataIndex: 'unloadWeight',
          width: 140,
        },
        {
          title: '趟次单价(元)',
          dataIndex: 'linePrice',
          width: 120,
        },
        {
          title: '拉运趟次',
          dataIndex: 'total',
          width: 120,
        },
        {
          title: '总收入(元)',
          dataIndex: 'taskPrice',
          width: 120,
        },
      ],
    },
    {
      title: '变动收本',
      children: [
        {
          title: '过路费(元)',
          dataIndex: 'roadPrice',
          width: 120,
        },
        {
          title: '司机工资(元)',
          dataIndex: 'driverPrice',
          width: 120,
        },
        {
          title: '电费(元)',
          dataIndex: 'chargePrice',
          width: 120,
        },
        {
          title: '维修(元)',
          dataIndex: 'repairPrice',
          width: 120,
        },
        {
          title: '轮胎(元)',
          dataIndex: 'tyrePrice',
          width: 120,
        },
        {
          title: '信息费(元)',
          dataIndex: 'infoPrice',
          width: 120,
        },
        {
          title: '装卸费(元)',
          dataIndex: 'loadAndUnloadPrice',
          width: 120,
        },
      ],
    },
    {
      title: '固定成本',
      children: [
        {
          title: '日折旧成本(元)',
          dataIndex: 'depreciationPrice',
          width: 140,
        },
        {
          title: '管理费用(元)',
          dataIndex: 'managePrice',
          width: 120,
        },
      ],
    },
    {
      title: '毛利润(元)',
      dataIndex: 'grossProfit',
      width: 120,
    },
    {
      title: '毛利率(%)',
      dataIndex: 'grossProfitRate',
      width: 120,
    },
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      children: <GroupTreeSelect placeholder="请选择组织" allowClear={false} />,
      formItemProps: {
        rules: [REQUIRED],
      },
    },
    {
      label: '开始日期',
      name: 'day',
      children: (
        <DatePicker
          allowClear={false}
          placeholder="请选择开始日期"
          format="YYYY-MM-DD"
        />
      ),
      formItemProps: {
        rules: [REQUIRED],
      },
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/dmm/operation/vehicle/daily/cost/export/list',
      method: 'GET',
      params,
    });
    if (res) {
      window.open(res);
    }
  };

  return (
    <>
      <Crud
        key={groupData?.[0]?.groupId}
        ref={crudRef}
        // rowKey="vehicleId"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            day: dayjs().subtract(1, 'day').startOf('day'),
            groupId: groupData?.[0]?.groupId,
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        tableProps={{
          pagination: false,
        }}
        transformParams={(params) => {
          return {
            ...params,
            index: 0,
            size: 0,
            day: params?.day?.format('YYYY-MM-DD'),
          };
        }}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </>
        }
      />
    </>
  );
};

export default Index;
